<template>
  <div class="order-list">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="table-container">
      <el-table
        v-loading="loading"
        :data="orderList"
        style="width: 100%"
      >
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getOrderStatusType(row.status)">
              {{ row.statusText }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleDetail(row.id)"
            >
              查看详情
            </el-button>
            <el-button
              v-if="row.canCancel"
              link
              type="danger"
              @click="handleForceCancel(row)"
            >
              强制取消
            </el-button>
            <el-button
              v-if="row.canRefund"
              link
              type="warning"
              @click="handleForceRefund(row)"
            >
              强制退款
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 强制取消对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="强制取消订单"
      width="500px"
    >
      <el-form
        ref="cancelFormRef"
        :model="cancelForm"
        :rules="cancelRules"
        label-width="100px"
      >
        <el-form-item label="取消原因" prop="reason">
          <el-input
            v-model="cancelForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入取消原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCancel" :loading="cancelSubmitting">
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 强制退款对话框 -->
    <el-dialog
      v-model="refundDialogVisible"
      title="强制退款"
      width="500px"
    >
      <el-form
        ref="refundFormRef"
        :model="refundForm"
        :rules="refundRules"
        label-width="100px"
      >
        <el-form-item label="退款金额">
          <span>¥{{ currentOrder?.payAmount }}</span>
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-input
            v-model="refundForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入退款原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund" :loading="refundSubmitting">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getAdminOrders, forceCancel, forceRefund } from '@/api/order'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  dateRange: []
})

// 数据相关
const loading = ref(false)
const orderList = ref([])
const total = ref(0)
const currentOrder = ref(null)

// 获取订单状态对应的标签类型
const getOrderStatusType = (status) => {
  const statusTypeMap = {
    0: 'info',    // 待支付
    1: 'warning', // 待发货
    2: 'primary', // 已发货
    3: 'success', // 已完成
    4: 'danger',  // 已取消
    5: 'warning', // 退款中
    6: 'info'     // 已退款
  }
  return statusTypeMap[status] || 'info'
}

// 获取订单列表
const getList = async () => {
  try {
    loading.value = true
    const [startTime, endTime] = queryParams.dateRange || []
    const response = await getAdminOrders({
      ...queryParams,
      startTime,
      endTime
    })
    if (response.code === 200) {
      orderList.value = response.data.records
      total.value = response.data.total
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateArray) => {
  if (!dateArray) return '--'
  if (Array.isArray(dateArray)) {
    const [year, month, day, hour, minute, second] = dateArray
    return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`
  }
  return dateArray
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.dateRange = []
  handleQuery()
}

// 分页操作
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 查看详情
const handleDetail = (id) => {
  router.push(`/admin/order/detail/${id}`)
}

// 强制取消相关
const cancelDialogVisible = ref(false)
const cancelSubmitting = ref(false)
const cancelForm = reactive({
  reason: ''
})

const cancelRules = {
  reason: [
    { required: true, message: '请输入取消原因', trigger: 'blur' }
  ]
}

const handleForceCancel = (row) => {
  currentOrder.value = row
  cancelDialogVisible.value = true
  cancelForm.reason = ''
}

const confirmCancel = async () => {
  try {
    cancelSubmitting.value = true
    const response = await forceCancel(currentOrder.value.id, cancelForm.reason)
    if (response.code === 200) {
      ElMessage.success('取消成功')
      cancelDialogVisible.value = false
      getList()
    }
  } catch (error) {
    console.error('取消失败:', error)
    ElMessage.error('取消失败')
  } finally {
    cancelSubmitting.value = false
  }
}

// 强制退款相关
const refundDialogVisible = ref(false)
const refundSubmitting = ref(false)
const refundForm = reactive({
  reason: ''
})

const refundRules = {
  reason: [
    { required: true, message: '请输入退款原因', trigger: 'blur' }
  ]
}

const handleForceRefund = (row) => {
  currentOrder.value = row
  refundDialogVisible.value = true
  refundForm.reason = ''
}

const confirmRefund = async () => {
  try {
    refundSubmitting.value = true
    const response = await forceRefund(currentOrder.value.id, refundForm.reason)
    if (response.code === 200) {
      ElMessage.success('退款成功')
      refundDialogVisible.value = false
      getList()
    }
  } catch (error) {
    console.error('退款失败:', error)
    ElMessage.error('退款失败')
  } finally {
    refundSubmitting.value = false
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.order-list {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 